package com.kayak.emailWorks.util;

import java.security.Security;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 发送HTML格式的邮件
 * */
public class SendEmailHtml {
	
	protected final static Logger log = LoggerFactory.getLogger(SendEmailHtml.class);
	@SuppressWarnings("restriction")
	public  void sendAEmail(final String username, final String password,
			String title, String content, String toUser) {		
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());    
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
		String host = "smtp.263.net";
		int port = 465;
		String from = username;
		boolean isAuth = true;
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", isAuth);
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);    
        props.put("mail.smtp.socketFactory.fallback", "false");  
        props.put("mail.smtp.socketFactory.port", "465");
		Session session = Session.getInstance(props, new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
			}
		});
		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					toUser));
			message.setSubject(title);
			message.setText(content);		
			Transport tran = session.getTransport("smtp");
			tran.connect(host, username, password);
			Multipart mainPart = new MimeMultipart();
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setContent(content,"text/html; charset=utf-8");  
			mainPart.addBodyPart(messageBodyPart);
			message.setContent(mainPart);
			tran.sendMessage(message, message.getAllRecipients());
			tran.close();
			log.info(toUser+"发送成功");
		} catch (AddressException e) {
			log.info("邮件地址不合法");
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
